//
//  HNLoginController.m
//  shezhan
//
//  Created by admin on 16/8/25.
//  Copyright © 2016年 haoniu. All rights reserved.
//

#import "HNLoginController.h"
#import "ChatDemoHelper.h"

#import "JPUSHService.h"

@interface HNLoginController ()<UIWebViewDelegate>{
    NSDictionary * _userInfo;
}

@end

@implementation HNLoginController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _webViewUrl = [NSMutableString stringWithFormat:@"%@%@",url_Base,url_Login];
    NSLog(@"------%@",_webViewUrl);
    _webViewUrl = [NSMutableString stringWithFormat:@"%@",[_webViewUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest * _req = [NSURLRequest requestWithURL:[NSURL URLWithString:_webViewUrl]];
    _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, mainScreenSize.width, mainScreenSize.height)];
    [_webView loadRequest:_req];
    _webView.scrollView.bounces = NO;
    _webView.delegate = self;
    [_webView setBackgroundColor:[AppConfig colorWithHexString:@"#ececec"]];
    [self.view addSubview:_webView];
}

#pragma -mark WebView
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    NSLog(@"WebView erros is %@",error);
    if ([error code] == NSURLErrorCancelled) {
        return;
    }
    // 应用场景:加载从服务器上下载的文件,例如pdf,或者word,图片等等文件
    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"error" ofType:@"html"];
    NSString *htmlString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    [webView loadHTMLString:htmlString baseURL:[NSURL URLWithString:filePath]];
}
-(void)webViewDidFinishLoad:(UIWebView *)webView{
    // Disable user selection
    [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none';"];
    // Disable callout
    [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none';"];
    //JS交互
    JSContext *context=[webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    context[@"JavaScriptInterface"]=self;
}
- (BOOL)webView: (UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSString *_str = [[request URL] absoluteString];
    NSLog(@"===Start==========123:%@",request);
    if ([[_str substringToIndex:5] isEqualToString:@"file:"]) {
        return YES;
    }else if ([_str isEqualToString:_webViewUrl]) {
        return YES;
    }
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma -mark JS返回登录结果
-(void)HNLoginJSExportLoginResult:(NSNumber *)success WithUserInfo:(NSString *)data{
    
    NSLog(@"HNLoginJSExportLoginResult:%@,%@",success,data);
    
    NSDictionary *userInfo = [AppConfig dictionaryWithJsonString:data];
    _userInfo = userInfo;
    if (_userInfo) {
        
       
        
        [self loginWithUsername:[_userInfo objectForKey:@"hnLoginName"] password:[_userInfo objectForKey:@"hnLoginPwd"]];
        //[self loginWithUsername:@"duhuan" password:@"123456"];
        
        
    }
    
}


#pragma -mark 登录环信
//点击登陆后的操作
- (void)loginWithUsername:(NSString *)username password:(NSString *)password
{
    //当前的登录名

    [self showHudInView:self.view hint:nil];//NSLocalizedString(@"login.ongoing", @"Is Login...")
    //异步登陆账号
    __weak typeof(self) weakself = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        EMError *error = [[EMClient sharedClient] loginWithUsername:username password:password];
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakself hideHud];
            if (!error) {
                //设置是否自动登录
                [[EMClient sharedClient].options setIsAutoLogin:YES];
                
                //获取数据库中数据
                [self showHudInView:self.view hint:nil];
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    [[EMClient sharedClient] dataMigrationTo3];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [[ChatDemoHelper shareHelper] asyncGroupFromServer];
                        [[ChatDemoHelper shareHelper] asyncConversationFromDB];
                        [[ChatDemoHelper shareHelper] asyncPushOptions];
                        [self hideHud];
                        //发送自动登陆状态通知
                        [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@([[EMClient sharedClient] isLoggedIn])];
                        
                        //保存最近一次登录用户名
                        [weakself saveLastLoginUsername];
                        
                        [AppConfig saveUserInfo:_userInfo];
//                          [self downLoadUserInfo];
                        
                    });
                });
            } else {
                switch (error.code)
                {
                        //                    case EMErrorNotFound:
                        //                        TTAlertNoTitle(error.errorDescription);
                        //                        break;
                    case EMErrorNetworkUnavailable:
                        TTAlertNoTitle(NSLocalizedString(@"error.connectNetworkFail", @"No network connection!"));
                        break;
                    case EMErrorServerNotReachable:
                        TTAlertNoTitle(NSLocalizedString(@"error.connectServerFail", @"Connect to the server failed!"));
                        break;
                    case EMErrorUserAuthenticationFailed:
                        TTAlertNoTitle(error.errorDescription);
                        break;
                    case EMErrorServerTimeout:
                        TTAlertNoTitle(NSLocalizedString(@"error.connectServerTimeout", @"Connect to the server timed out!"));
                        break;
                    default:
                        TTAlertNoTitle(NSLocalizedString(@"login.fail", @"Login failure"));
                        break;
                }
            }
        });
    });
}



#pragma  mark - private
- (void)saveLastLoginUsername
{
    NSString *username = [[EMClient sharedClient] currentUsername];
    if (username && username.length > 0) {
        NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
        [ud setObject:username forKey:[NSString stringWithFormat:@"em_lastLogin_username"]];
        [ud synchronize];
    }
}

- (NSString*)lastLoginUsername
{
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    NSString *username = [ud objectForKey:[NSString stringWithFormat:@"em_lastLogin_username"]];
    if (username && username.length > 0) {
        return username;
    }
    return nil;
}


@end
